package com.hontech.pastacooking.activity.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.Button
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import com.hontech.pastacooking.R
import com.hontech.pastacooking.activity.window.showProg
import com.hontech.pastacooking.app.onClick
import com.hontech.pastacooking.app.toInt
import com.hontech.pastacooking.conn.rkcRead
import com.hontech.pastacooking.conn.rkcWrite
import com.hontech.pastacooking.ext.signedValue16
import com.hontech.pastacooking.ext.unsignedValue16
import com.hontech.pastacooking.utils.S

class InputFormView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    private val mText: TextView
    private val mInput: EditText
    private val mBtnRead: Button
    private val mBtnWrite: Button

    private val mReg: Int
    private val mSigned: Boolean
    private val mBase: Int

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.view_input_form, this)
        mText = view.findViewById(R.id.id_input_form_label)
        mInput = view.findViewById(R.id.id_input_form_input)
        mBtnRead = view.findViewById(R.id.id_btn_form_read)
        mBtnWrite = view.findViewById(R.id.id_btn_form_write)

        val attr = context.obtainStyledAttributes(attrs, R.styleable.InputFormView)

        val text = attr.getText(R.styleable.InputFormView_title)
        mText.setText(text.toString())

        val reg = attr.getText(R.styleable.InputFormView_reg).toString()
        mReg = reg.toInt(16)

        mSigned = attr.getBoolean(R.styleable.InputFormView_signed, true)
        mBase = attr.getInt(R.styleable.InputFormView_base, 1)

        attr.recycle()
        mBtnRead.onClick(::onRead)
        mBtnWrite.onClick(::onWrite)
    }

    suspend fun onWrite() {

        val w = showProg(mBtnRead, "${S.t139}${mText.text}")
        try {
            val value = (mInput.toInt() * mBase).unsignedValue16()
            rkcWrite(mReg, value)
            w.success("${S.t139}${mText.text}${S.t140}")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    suspend fun onRead() {
        val w = showProg(mBtnRead, "${S.t141}${mText.text}")
        try {
            val value = rkcRead(mReg).signedValue16()
            val text = (value / mBase).toString()
            mInput.setText(text)
            w.success("${S.t141}${mText.text}${S.t140} $text")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }
}